package framework.common;

abstract public class DeviceServer implements Runnable {

	private String deviceName;
	private HubServer hub;
	private Sensor sensor;

	public String getDeviceName() {
		return deviceName;
	}

	/**
	 * このデバイスに全体で一意な名前を付ける。
	 *
	 * @param deviceName
	 *            デバイス名
	 */
	public void setDeviceName(String deviceName) {
		this.deviceName = deviceName;
	}

	abstract public void start();

	abstract public void stop();

	public HubServer getHub() {
		return hub;
	}

	public void setHub(HubServer hub) {
		this.hub = hub;
	}

	public Sensor getSensor() {
		return sensor;
	}

	public void setSensor(Sensor sensor) {
		this.sensor = sensor;
		sensor.setDevice(this);
	}

	/**
	 * このデバイスをユーザの所有物として登録する。
	 *
	 * @param user
	 *            ユーザ識別子
	 */
	public void register(String user) {
		hub.register(user, this);
	}

	public void service(DeviceRequest request, DeviceResponse response) {
		if (sensor == null) {
			response.add(new SensorResponse(SensorResponse.ERR, "reason",
					"disconnected"));
		} else {
			for (SensorRequest req : request.getRequests()) {
				SensorResponse res = sensor.sense(req);
				response.add(res);
			}
		}
	}

	public void putResponse(DeviceResponse res) {
		hub.putResponse(res);
	}

	public DeviceRequest getRequest() {
		return hub.getRequest(this);
	}

	public boolean hasRequest() {
		return hub.hasRequest(this);
	}

}
